package app1.rapidsquare.com.activity;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

import app1.rapidsquare.com.adapter.AgileFragmentPagerAdapter;
import app1.rapidsquare.com.adapter.SideNavigationAdapter;
import app1.rapidsquare.com.Utility.Utility;
import app1.rapidsquare.com.activity.R;
import app1.rapidsquare.com.classes.User;
import app1.rapidsquare.com.fragment.AgileDayFragment;
import app1.rapidsquare.com.fragment.ContactFragment;
import app1.rapidsquare.com.fragment.EventFragment;
import app1.rapidsquare.com.fragment.ProfileFragment;


public class MainActivity extends AgileActivity implements ViewPager.OnPageChangeListener {

    public ViewPager mViewPager;
    private ListView mSideNavigationListView;
    private ArrayList<String> mSideNavigationItems = new ArrayList<String>();
    private LinearLayout mSideNagivationView;
    private RelativeLayout mSideNagivationContainerView;
    private View mSideNagivationViewOut;
    private SideNavigationAdapter mSideNavigationAdapter;
    public TextView mTextViewInternetConnection;
    public AgileFragmentPagerAdapter mFragmentPagerAdapter;
    private AlertDialog alertDialog;
    private volatile ArrayList<User> notificationList = new ArrayList<User>();
    private ImageView mImageViewHide;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextViewInternetConnection = (TextView) findViewById(R.id.textViewInternetConnection);
        mTextViewInternetConnection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mTextViewInternetConnection.setVisibility(View.GONE);
            }
        });
        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        mSideNagivationContainerView = (RelativeLayout) findViewById(R.id.relativeLayoutContainer);
        mSideNagivationView = (LinearLayout) findViewById(R.id.linearLayoutSideNavigationView);
        mSideNagivationViewOut = findViewById(R.id.viewSideNavigationOut);
        mSideNagivationViewOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                HideMenu();
            }
        });
        mSideNavigationListView = (ListView) findViewById(R.id.listViewSideNavigation);
        mSideNavigationListView.setOnItemClickListener(mSideNagivationItemClickListener);
        LoadSideNavigationItem();
        mSideNavigationAdapter = new SideNavigationAdapter(MainActivity.this, mSideNavigationItems);
        mSideNavigationListView.setAdapter(mSideNavigationAdapter);
        mImageViewHide = (ImageView) findViewById(R.id.imageViewHide);

        mFragmentPagerAdapter = new AgileFragmentPagerAdapter(this, getSupportFragmentManager());
        mViewPager.setAdapter(mFragmentPagerAdapter);
        mViewPager.setOnPageChangeListener(this);
        int startPosition = mFragmentPagerAdapter.getPosition(EventFragment.class);
        if (startPosition == -1)
            startPosition = 1;
        mViewPager.setCurrentItem(startPosition);
        mImageViewLogo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToogleMenu();
            }
        });
        mImageViewHide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToogleMenu();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        LocalBroadcastManager.getInstance(this).registerReceiver(mNotificationBroadCastReceiver,
                new IntentFilter(Utility.NOTIFICATION_BROADCASTRECEIVER_ACTION));
        if (!IsAvailableInternet())
            mTextViewInternetConnection.setVisibility(View.VISIBLE);
        else
            mTextViewInternetConnection.setVisibility(View.GONE);

        CheckNotification();
    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mNotificationBroadCastReceiver);
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (requestCode == Utility.SOCIAL_ACTIVITY_REQUEST_CODE && resultCode != RESULT_OK) {
            mViewPager.setCurrentItem(mFragmentPagerAdapter.getPosition(EventFragment.class));
        }

        if (requestCode == Utility.SOCIAL_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
            if (data != null && data.hasExtra(Utility.SOCIAL_INTENT_DATA_NAME)) {

                User user = (User) data.getSerializableExtra(Utility.SOCIAL_INTENT_DATA_NAME);
                Utility.setUserSession(getApplicationContext(), user);

                ProfileFragment fragment = (ProfileFragment) mFragmentPagerAdapter.instantiateItem(mViewPager, mFragmentPagerAdapter.getPosition(ProfileFragment.class));
                mViewPager.setCurrentItem(mFragmentPagerAdapter.getPosition(ProfileFragment.class));
                if (fragment != null) {
                    Bundle savedInstanceState = new Bundle();
                    savedInstanceState.putSerializable(Utility.PROFILE_DATA_SAVEDINSTANCESTATE, user);
                    fragment.onActivityCreated(savedInstanceState);
                }
            }
        }

        if (requestCode == Utility.VIEW_INFO_ACTIVITY_REQUEST_CODE && data != null) {
            User user = (User) data.getSerializableExtra(Utility.CONTACT_DATA_INTENT_DATA_NAME);
            for (User notificationItem : notificationList) {
                if (notificationItem.Id == user.Id) {
                    notificationList.remove(notificationItem);
                    break;
                }
            }
            alertDialog.dismiss();
            alertDialog = null;
            ShowNotification();
            if (resultCode == RESULT_OK) {

                if (mFragmentPagerAdapter != null) {
                    ContactFragment fragment = (ContactFragment) mFragmentPagerAdapter.instantiateItem(mViewPager, mFragmentPagerAdapter.getPosition(ContactFragment.class));
                    if (fragment != null) {
                        fragment.SendRequestToLoadContacts();
                    }
                }
            }
        }

        if (requestCode == 64206) {
            ProfileFragment fragment = (ProfileFragment) mFragmentPagerAdapter.instantiateItem(mViewPager, mFragmentPagerAdapter.getPosition(ProfileFragment.class));
            if (fragment != null) {
                if (resultCode == RESULT_CANCELED)
                    fragment.onLoadComplete(null);

                if (resultCode == RESULT_OK)
                    fragment.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

    @Override
    protected void getResponce(String result) {
        alertDialog.dismiss();
        alertDialog = null;
        CheckNotification();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                ToogleMenu();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (IsShown()) {
            HideMenu();
        } else {
            super.onBackPressed();
            finish();
        }
    }

    private void LoadSideNavigationItem() {
        mSideNavigationItems.add(getResources().getString(
                R.string.connections));
        mSideNavigationItems.add(getResources().getString(
                R.string.events));
        mSideNavigationItems.add(getResources().getString(
                R.string.about_agile_day));
        mSideNavigationItems.add(getResources().getString(
                R.string.my_profile));
        mSideNavigationItems.add(getResources().getString(
                R.string.how_it_works));

//        mSideNavigationItems.add(getResources().getString(R.string.settings));
    }

    final synchronized void ToogleMenu() {
        if (IsShown())
            HideMenu();
        else
            ShowMenu();
    }

    final synchronized void ShowMenu() {
        mSideNagivationContainerView.setVisibility(View.VISIBLE);
        mSideNagivationViewOut.setVisibility(View.VISIBLE);
        mSideNagivationViewOut.startAnimation(AnimationUtils.loadAnimation(MainActivity.this,
                R.anim.side_navigation_fade_in));
        mSideNagivationView.setVisibility(View.VISIBLE);
        mSideNagivationView.startAnimation(AnimationUtils.loadAnimation(
                MainActivity.this, R.anim.side_navigation_in_from_left));

    }

    private synchronized void HideMenu() {
        mSideNagivationView.setVisibility(View.GONE);
        mSideNagivationView.startAnimation(AnimationUtils.loadAnimation(MainActivity.this,
                R.anim.side_navigation_fade_out));
        mSideNagivationView.setVisibility(View.GONE);
        mSideNagivationView.startAnimation(AnimationUtils.loadAnimation(
                MainActivity.this, R.anim.side_navigation_out_to_left));
        mSideNagivationContainerView.setVisibility(View.GONE);
    }

    private synchronized boolean IsShown() {
        return mSideNagivationView.isShown();
    }

    private AdapterView.OnItemClickListener mSideNagivationItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            if (position == mFragmentPagerAdapter.getCount()) {
                GoToHowToWorks();
            } else {
                if (CheckAuthentification(position))
                    mViewPager.setCurrentItem(position);
            }
            HideMenu();
        }
    };

    private void GoToHowToWorks() {
        Intent intent = new Intent(MainActivity.this, HowItWorksActivity.class);
        startActivity(intent);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (CheckAuthentification(position)) {

            if (mSideNavigationAdapter != null) {
                mSideNavigationAdapter.setSelectedItemPosition(position);
            }
            ChangeMenuImage(position);
        }
        HideKeyboard();

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private void ChangeMenuImage(int position) {
      /*  if (position == mFragmentPagerAdapter.getPosition(AgileDayFragment.class)) {
            setTitle("");
            mImageViewMenu.setImageResource(R.drawable.logo_landscape);
            mImageViewMenu.setClickable(false);
        }*/

        if (position == mFragmentPagerAdapter.getPosition(ContactFragment.class) || position == mFragmentPagerAdapter.getPosition(ProfileFragment.class) || position == mFragmentPagerAdapter.getPosition(EventFragment.class)) {
            String code = Utility.getUserSession(MainActivity.this).Code;
            if (!Utility.isNullOrEmpty(code)) {
                setTitle(code);
                mImageViewMenu.setOnClickListener(ConnectDialogOnClickListener);
            } else {
                mImageViewMenu.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        CheckAuthentification(mFragmentPagerAdapter.getPosition(ProfileFragment.class));
                    }
                });
            }
            mImageViewMenu.setImageResource(R.drawable.connect);
        }
    }

    private final boolean CheckAuthentification(int position) {
        if (!IsAuthentication() && (position == mFragmentPagerAdapter.getPosition(ContactFragment.class) || position == mFragmentPagerAdapter.getPosition(ProfileFragment.class))) {
            Intent intent = new Intent(MainActivity.this, SocialActivity.class);
            startActivityForResult(intent, Utility.SOCIAL_ACTIVITY_REQUEST_CODE);
            mViewPager.setCurrentItem(mFragmentPagerAdapter.getPosition(EventFragment.class));
            return false;
        }
        return true;
    }

    private void CheckNotification() {

        if (IsAvailableInternet()) {
            final String userCode = Utility.getUserSession(getApplicationContext()).Code;

            if (!Utility.isNullOrEmpty(userCode)) {
                new AsyncTask<Void, Void, String>() {
                    @Override
                    protected String doInBackground(Void... voids) {
                        return Utility.ConnectServer(Utility.CHECK_NOTIFICATION_URL + "?userToken=" + Utility.getUserSession(getApplicationContext()).UserToken, Utility.RequestMethodType.GET, null);
                    }

                    @Override
                    protected void onPostExecute(String result) {
                        if (!Utility.isNullOrEmpty(result)) {
                            try {
                                JSONObject jObject = new JSONObject(result);
                                if (jObject.has("Result"))
                                    result = jObject.getString("Result");
                                if (!result.equals("No Notification")) {
                                    if (!Utility.isNullOrEmpty(result) && result.contains("[")) {
                                        JSONArray jsonArray = new JSONArray(result);
                                        for (int i = 0; i < jsonArray.length(); i++) {
                                            JSONObject jsonObject = jsonArray
                                                    .getJSONObject(i);
                                            User userAbout = Utility.Deserialize(User.class, jsonObject.toString());
                                            if (userAbout != null && Utility.isNullOrEmpty(userAbout.Status) && !ContainsNotification(userAbout)) {
                                                notificationList.add(userAbout);
                                            }
                                        }
                                    } else {
                                        User userAbout = Utility
                                                .Deserialize(User.class, result);
                                        if (userAbout != null && Utility.isNullOrEmpty(userAbout.Status) && !ContainsNotification(userAbout)) {
                                            notificationList.add(userAbout);
                                        }
                                    }
                                }
                            } catch (Exception ex) {
                                Utility.Log("Notication json convert error in GsmMessageService", ex);
                            }
                        }

                        ShowNotification();
                    }
                }.execute();
            }
        }
    }

    private boolean ContainsNotification(User user) {
        for (int i = 0; i < notificationList.size(); i++) {
            if (notificationList.get(i).Code.equals(user.Code))
                return true;
        }

        return false;
    }

    private int IndexOfNotification(User user) {
        for (int i = 0; i < notificationList.size(); i++) {
            if (notificationList.get(i).Code.equals(user.Code))
                return i;
        }

        return -1;
    }

    private void ShowNotification() {
        for (int i = 0; i < notificationList.size(); i++) {
            final User userNotification = notificationList.get(i);
            if (alertDialog == null) {
                ShowNotificationDialog(userNotification);
            }
        }
    }

    private void ShowNotificationDialog(final User notificationData) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            alertDialog = new AlertDialog.Builder(MainActivity.this, AlertDialog.THEME_HOLO_LIGHT).create();
        else
            alertDialog = new AlertDialog.Builder(MainActivity.this).create();
        alertDialog.setInverseBackgroundForced(true);
        alertDialog.setCancelable(false);

        String title = getResources().getString(R.string.connection_request_message);

        String fullName = notificationData.FirstName + " " + notificationData.LastName;

        View viewTitle = getLayoutInflater().inflate(R.layout.dialog_notification_title, null);
        TextView textViewTitle = (TextView) viewTitle.findViewById(R.id.textViewDialogTitle);
        textViewTitle.setText(String.format(title, fullName));
        alertDialog.setCustomTitle(viewTitle);

        View view = getLayoutInflater().inflate(R.layout.dialog_notification, null);

        Button buttonAccept = (Button) view.findViewById(R.id.buttonAccept);
        buttonAccept.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OnAcceptOrIgnore(true, notificationData);
            }
        });
        Button buttonIgnore = (Button) view.findViewById(R.id.buttonIgnore);
        buttonIgnore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OnAcceptOrIgnore(false, notificationData);
            }
        });


        Button buttonViewInfo = (Button) view.findViewById(R.id.buttonViewInfo);
        buttonViewInfo.setEnabled(true);
        buttonViewInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
                intent.putExtra(Utility.CONTACT_DATA_INTENT_DATA_NAME, notificationData);
                intent.putExtra("IsConnectContact", true);
                startActivityForResult(intent, Utility.VIEW_INFO_ACTIVITY_REQUEST_CODE);
            }
        });
        alertDialog.setView(view);
        alertDialog.show();
    }

    private void OnAcceptOrIgnore(final boolean status, final User user) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = Utility.REPLY_NOTIFICATION_URL + "?userToken="
                        + Utility.getUserSession(MainActivity.this).UserToken + "&code="
                        + user.Code.trim() + "&agree=" + status;

                Utility.ConnectServer(url, Utility.RequestMethodType.GET, null);
                handler.sendEmptyMessage(0);
            }
        }).start();


        if (ContainsNotification(user)) {
            int index = IndexOfNotification(user);
            if (index != -1)
                notificationList.remove(index);
        }

        ContactFragment fragment = (ContactFragment) mFragmentPagerAdapter.instantiateItem(mViewPager, mFragmentPagerAdapter.getPosition(ContactFragment.class));
        if (fragment != null) {
            fragment.SendRequestToLoadContacts();
        }
        alertDialog.dismiss();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            alertDialog = null;
            CheckNotification();
        }
    };

    private BroadcastReceiver mNotificationBroadCastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String message = intent.getStringExtra("message");
            Utility.Info("received from gcm service", "Got notification: " + message);
            CheckNotification();
            if (mFragmentPagerAdapter != null) {
                ContactFragment fragment = (ContactFragment) mFragmentPagerAdapter.instantiateItem(mViewPager, mFragmentPagerAdapter.getPosition(ContactFragment.class));
                if (fragment != null) {
                    fragment.SendRequestToLoadContacts();
                }
            }
        }
    };

    public void GoToProfileActivityResult(Intent data) {
        onActivityResult(Utility.SOCIAL_ACTIVITY_REQUEST_CODE, RESULT_OK, data);
    }
}
